package easytalk.connectivity.facebook;


import java.util.List;

import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import com.facebook.api.FacebookRestClient;
import com.facebook.api.schema.FriendsGetResponse;
import common.BodySet;
import common.DiscussionSentence;
import common.Locutor;

import connection.AbstarctServerConnection;
import connection.ServerType;
import easytalk.dialogs.BrowserDialog;

public class FacebookConnection extends AbstarctServerConnection {

	public static String APPLICATION_ID =  "8ae054e76b881377dbc2e9521642a250";
	public static String APPLICATION_KEY = "844f176bfc7a776d412fa7cca2f8ab6d";
	
	private FacebookRestClient connection;
	private String sessionId;
	protected int result;
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void hookBodySet(BodySet set) throws Exception {
		
		connection.friends_get();
		
		 FriendsGetResponse response = (FriendsGetResponse)connection.getResponsePOJO();
		 
		 List<Long> listFriendsId = response.getUid();
		 for (Long id : listFriendsId ) {
			 Locutor locutor = set.createLocutor(id.toString());
			 locutor.setName("unkonwn yet");
			
		/*	 Document d =  connection.profile_getInfo(id);
			System.out.println(d.getTextContent());
			locutor.setName(d.getElementsByTagName("name").item(0).getTextContent());
			*/ 
		 }
		
	}

	@Override
	public boolean login(String username, String password) throws Exception {
		connection = new FacebookRestClient(APPLICATION_ID, APPLICATION_KEY);
		connection._setExpires(new Long(500000));
		connection.setIsDesktop(true);
		
		this.config.setServerType(ServerType.FACEBOOK);
		this.config.setUserName(username);
		this.config.setPassword(password);
		
			String token  = connection.auth_createToken();
			final String url = "http://www.new.facebook.com/login.php?api_key="+APPLICATION_ID+"&v=1.0&auth_token="+token;
			final Display display = PlatformUI.getWorkbench().getDisplay();
			display.syncExec(new Runnable() {

				@Override
				public void run() {
					Shell shell = new Shell(display,SWT.APPLICATION_MODAL);
					BrowserDialog dialog = new BrowserDialog(shell);
					dialog.setUrl(url);
					dialog.open();
					result=dialog.getReturnCode();
					
				}
				
			});
			if (result !=Window.OK)
				return false;
			sessionId = connection.auth_getSession(token);
			connection._setSessionKey(sessionId);
		
			
		return true;
	}

	@Override
	public void logout() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void createChat(String id) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void sendMessage(String id, DiscussionSentence sentence) {
		// TODO Auto-generated method stub
		
	}

}
